package com.lvmama.controller.rhino.position;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.lvmama.common.enums.CommonParentType;
import com.lvmama.common.result.CodeMessage;
import com.lvmama.common.result.Result;
import com.lvmama.common.utils.DateUtil;
import com.lvmama.pojo.entity.rhino.topic.PositionAnalysis;
import com.lvmama.service.rhino.topic.PositionAnalysisService;
import com.lvmama.service.rhino.topic.StatisticCodeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @param
 * @Title:
 * @Author:wangpeng
 * @Description: TODO(这里用一句话描述这个方法的作用)
 * @return
 * @throws
 */
@RestController
@Slf4j
@RequestMapping(value = "/positionAnalysis")
public class PositionAnalysisController {

	@Autowired
	StatisticCodeService iStatisticCodeService;

	@Autowired
    PositionAnalysisService positionAnalysisService;

	/**
	 * @Title: queryList
	 * @Description: 坑位列表
	 */
	@PostMapping(value = "queryList")
	Result<PageInfo<PositionAnalysis>> queryList(@RequestBody PositionAnalysis dto){
		log.info("queryList start");
		PageInfo<PositionAnalysis> result = null;
		// 查询日期条件处理
		Map<String, Date> dateMap = DateUtil.getQueryDate(dto.getChooseTime());
		try {
			Date beginDate = dateMap.get("beginDate");
			Date endDate = dateMap.get("endDate");
			dto.setStartDate(beginDate);
			dto.setEndDate(endDate);
			dto = handlePlatforms(dto);
			result = positionAnalysisService.getPitList(dto);
		}catch (Exception e){
			log.error("queryList error",e.getMessage(),e);
			return Result.error(CodeMessage.SERVER_ERROR);
		}
		log.info("queryList end");
		return Result.success(result);
	}

	/**
	 * 图表数据
	 * @return
	 * @throws Exception
	 */
	@PostMapping("chartData")
	public Result<Map<String, Object>> chartData(@RequestBody PositionAnalysis dto){
		log.info("chartData start");
		Map<String, Object> resultMap = new HashMap<>();
		// 查询日期条件处理
		Map<String, Date> dateMap = DateUtil.getQueryDate(dto.getChooseTime());
		try {
			Date beginDate = dateMap.get("beginDate");
			Date endDate = dateMap.get("endDate");
			dto.setStartDate(beginDate);
			dto.setEndDate(endDate);
			dto = handlePlatforms(dto);
			dto.setPlatform("pit");
			List<PositionAnalysis> pitListByCategory = positionAnalysisService.getPitListByCategory(dto);
			List<PositionAnalysis> pitListByDate = positionAnalysisService.getPitListByDate(dto);
			List<PositionAnalysis> pitBarByCategory = positionAnalysisService.getPitBarByCategory(dto);
			// 总订单量 总订单金额
			int payAmountTotal = 0;
			double payMoneyTotal = 0;
			// 饼状图数据
			JSONArray payAmountArr = new JSONArray();
			JSONArray payMoneyArr = new JSONArray();
			if(pitListByCategory!=null)
				for (PositionAnalysis positionAnalysis : pitListByCategory) {
					if(positionAnalysis ==null || positionAnalysis.getPayMoney() == null) continue;
					JSONObject payAmountOb = new JSONObject();
					JSONObject payMoneyOb = new JSONObject();
					payAmountTotal += positionAnalysis.getPayAmount();
					payMoneyTotal += positionAnalysis.getPayMoney();
					payAmountOb.put("categoryName", CommonParentType.getCategoryShowName(positionAnalysis.getCategoryId()));
					payAmountOb.put("amount",positionAnalysis.getPayAmount());
					payAmountArr.add(payAmountOb);
					payMoneyOb.put("categoryName",CommonParentType.getCategoryShowName(positionAnalysis.getCategoryId()));
					payMoneyOb.put("amount",positionAnalysis.getPayMoney());
					payMoneyArr.add(payMoneyOb);
				}
			// 柱状图数据
			List<String> categoryNames = new ArrayList<>();
			JSONArray arr2 = new JSONArray();
			if(pitBarByCategory != null)
				for (PositionAnalysis positionAnalysis : pitBarByCategory) {
					String categoryName = CommonParentType
							.getCategoryShowName(positionAnalysis.getCategoryId());
					if(StringUtils.isNotEmpty(categoryName)){
						categoryNames.add(categoryName);
						JSONObject o = new JSONObject();
						o.put("categoryName",categoryName);
						o.put("amount",positionAnalysis.getCompletedPaymentPageSum()
								+ positionAnalysis.getDetailPageSum()
								+ positionAnalysis.getFillOrderPageSum()
								+ positionAnalysis.getPendingPaymentPageSum());
						arr2.add(o);
					}
				}
			// 折线图数据
			String[] dateAxis = DateUtil.getBetweenTime(beginDate, endDate,
					"yyyy/MM/dd");
			List<String> dateList = Arrays.asList(dateAxis);
			JSONArray arr = new JSONArray();
			for(String date:dateList){
				for (String category : categoryNames) {
					Integer amount= 0;
					for (PositionAnalysis position : pitListByDate) {
						String categoryName = CommonParentType
								.getCategoryShowName(position.getCategoryId());
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
						String time = sdf.format(position.getTime());
						if (category.equals(categoryName) && date.equals(time)) {
							amount += position.getCompletedPaymentPageSum()
									+ position.getDetailPageSum()
									+ position.getFillOrderPageSum()
									+ position.getPendingPaymentPageSum();
						}
					}
					JSONObject o = new JSONObject();
					o.put("categoryName",category);
					o.put("time",date);
					o.put("amount",amount);
					arr.add(o);
				}
			}
			resultMap.put("payAmountTotal", payAmountTotal);
			resultMap.put("payMoneyTotal", payMoneyTotal);
			resultMap.put("jsonData",arr);
			resultMap.put("jsonData2",arr2);
			resultMap.put("payAmountJsonData",payAmountArr);
			resultMap.put("payMoneyJsonData",payMoneyArr);
		}catch (Exception e){
			log.error("chartData error",e.getMessage(),e);
		}
		log.info("chartData end");
		return Result.success(resultMap);
	}

	/**
	 * @Title: getPageChartData
	 * @Description: 根据品类获取相关页面的引流
	 * @return Map<String,Object> 返回类型
	 */
	@PostMapping("getPageChartData")
	Result<Map<String, Object>> getPageChartData(@RequestBody PositionAnalysis dto){
		log.info("getPageChartData start");
		Map<String, Object> resultMap = new HashMap<>();
		try {
			// 查询日期条件处理
			Map<String, Date> dateMap = DateUtil.getQueryDate(dto.getChooseTime());
			Date beginDate = dateMap.get("beginDate");
			Date endDate = dateMap.get("endDate");
			dto.setStartDate(beginDate);
			dto.setEndDate(endDate);
			dto = handlePlatforms(dto);
			dto.setPlatform("pit");
			dto.setCategoryId(CommonParentType.getCategoryValueByShowName(dto.getCategoryName()));
			PositionAnalysis pitForPage = positionAnalysisService.getPageNumByCategory(dto);
			resultMap.put("pitForPage", pitForPage);
		}catch (Exception e){
			log.error("getPageChartData error",e.getMessage(),e);
			return Result.error(CodeMessage.SERVER_ERROR);
		}
		log.info("getPageChartData end");
		return Result.success(resultMap);
	}

	@PostMapping("queryDetailByCode")
	Result<List<PositionAnalysis>> queryDetailByCode(@RequestBody PositionAnalysis dto){
		List<PositionAnalysis>  result = null;
		try{
			// 查询日期条件处理
			Map<String, Date> dateMap = DateUtil.getQueryDate(dto.getChooseTime());
			Date beginDate = dateMap.get("beginDate");
			Date endDate = dateMap.get("endDate");
			dto.setStartDate(beginDate);
			dto.setEndDate(endDate);
			result = positionAnalysisService.queryDetailByCode(dto);
		}catch (Exception e){
			log.error("queryDetailByCode error",e.getMessage(),e);
			return Result.error(CodeMessage.SERVER_ERROR);
		}
		return Result.success(result);
	}

	/**
	 * 处理前端传来,具有平台的情况
	 * @param positionAnalysis
	 * @return
	 */
	private PositionAnalysis handlePlatforms(PositionAnalysis positionAnalysis){
		if (StringUtils.isNotEmpty(positionAnalysis.getPlatform())) {
			List<String> statisticCodeList = new ArrayList<>();
			String[] platforms = StringUtils.split(positionAnalysis.getPlatform(),",");
			for(String pf:platforms){
				List<String> temp = iStatisticCodeService.getDeviceCodeByLikeName(pf);
				if(temp!=null && temp!= null)
					statisticCodeList.addAll(temp);
			}
			positionAnalysis.setStatisticCodeList(statisticCodeList);
		}
		return positionAnalysis;
	}
}
